package com.huadao.pda.data.http;

import android.content.Context;

import com.huadao.pda.R;
import com.huadao.pda.common.GsonUtil;
import com.huadao.pda.common.UtilHelpers;
import com.huadao.pda.common.gsonConverter.RockGsonConverterFactory;
import com.huadao.pda.main.PdaApplication;
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;

public class RetrofitHelper {
    private Context mContext;

    private static RetrofitHelper instance = null;
    private static Retrofit mRetrofit = null;

    public static final int DEFAULT_TIME = 3;    //默认超时时间

    public static RetrofitHelper getInstance(Context context) {
        if (instance == null) {
            instance = new RetrofitHelper(context);
        }
        return instance;
    }

    private RetrofitHelper(Context context) {
        mContext = context;
        init();
    }

    //在获得Dev-Id后重新设置一下
    public void reInit(){
        init();
    }

    private void init() {
        OkHttpClient.Builder builder = new OkHttpClient().newBuilder();
        //设置SSL
//        HttpsUtils.SSLParams sslParams=HttpsUtils.getSslSocketFactory();
//        builder.sslSocketFactory(sslParams.sSLSocketFactory,sslParams.trustManager);
        builder.readTimeout(DEFAULT_TIME, TimeUnit.SECONDS);
        builder.connectTimeout(DEFAULT_TIME, TimeUnit.SECONDS);
        builder.addInterceptor(new BasicParamsInterceptor.Builder().addHeaderParam("Token",PdaApplication.getInstance().getToken()).addHeaderParam("Dev-Type","PDA").addHeaderParam("MAC",UtilHelpers.getMacDefault(PdaApplication.getInstance())).addHeaderParam("Dev-Id",PdaApplication.getInstance().getDevKeyId()).build());
        builder.addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY));
        OkHttpClient okHttpClient = builder.build();
        mRetrofit = new Retrofit.Builder()
                .baseUrl(mContext.getString(R.string.url_base))
                .client(okHttpClient)
//                .addConverterFactory(RockGsonConverterFactory.create())
                .addConverterFactory(RockGsonConverterFactory.create(GsonUtil.getInstance().getGson()))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
    }

    private Map<String, String> getCommonMap() {
        if(PdaApplication.getInstance().getToken()==null){
            return null;
        }
        Map<String,String> map=new HashMap<>();
        map.put("token",PdaApplication.getInstance().getToken());
        return map;
    }

    public <T>T create(Class<T> service) {
        return mRetrofit.create(service);
    }

}
